/*
   This file is part of the 'Let's Do Stuff Together' project
   http://code.google.com/p/dostufftogether/

   Copyright 2010 Christoph Fuchs, Stefan Thaler

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package com.appspot.android2gather;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.appspot.android2gather.activity.RequestParameters;
import com.appspot.android2gather.configuration.ServerConfiguration;
import com.appspot.android2gather.location.ActivityLocationListener;
import com.appspot.android2gather.shared.ActivityImpl;
import com.appspot.android2gather.util.QueryHelper;

/**
 * Search for nearest activities and display them in a list.
 * 
 * @author Christoph 'Gigi' Fuchs
 * 
 */
public class ActivitiesInSurrounding extends ListActivity {

	/* Constants used to pass data to the activity detail view */
	protected static final String CLICKED_ACTIVITY_TITLE = "title";
	protected static final String CLICKED_ACTIVITY_DESCRIPTION = "description";
	protected static final String CLICKED_ACTIVITY_TIME_START = "startTime";
	protected static final String CLICKED_ACTIVITY_TIME_END = "endTime";
	protected static final String CLICKED_ACTIVITY_LATITUDE = "lat";
	protected static final String CLICKED_ACTIVITY_LONGITUDE = "long";
	protected static final String CLICKED_ACTIVITY_ALTITUDE = "alt";

	protected static final int CLICKED_ACTIVITY = 333;

	/* Location related */
	private LocationManager mlocManager;
	private ActivityLocationListener mlocListener;
	private Location lastKnownLocation;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// get users current position
		mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		mlocListener = new ActivityLocationListener();
		mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
				mlocListener);

		lastKnownLocation = mlocManager
				.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		if (lastKnownLocation != null)
			Log.v("LocalActivities", "Searching for activities around "
					+ lastKnownLocation.getLatitude() + ", "
					+ lastKnownLocation.getLongitude() + " (lat, long)");

		// query server for activities in surrounding
		String responseString = QueryHelper.queryServer(this.getBaseContext(),
				getRequestUri());

		final ActivityImpl[] foundActivities = QueryHelper.parseResponse(
				ActivityImpl[].class, responseString, this.getBaseContext());
		if (foundActivities != null) {

			List<String> activityTitles = new LinkedList<String>();

			for (ActivityImpl activity : foundActivities) {
				activityTitles.add(activity.getName()+" ("+activity.getNumberOfAttendees()+")");
			}

			String[] activityTitlesArray = new String[foundActivities.length];
			setListAdapter(new ArrayAdapter<String>(this,
					R.layout.simplelistitem,
					activityTitles.toArray(activityTitlesArray)));

			ListView lv = getListView();
			lv.setTextFilterEnabled(true);

			lv.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// When clicked, redirect to activity detail view
					// ShowActivity
					Log.i("View", "Switching to activity detail view");
					Intent showActivityIntent = new Intent(view.getContext(),
							ShowActivity.class);
					ActivityImpl clickedActivity = foundActivities[position];
					showActivityIntent.putExtra(CLICKED_ACTIVITY_TITLE,
							clickedActivity.getName());
					showActivityIntent.putExtra(CLICKED_ACTIVITY_DESCRIPTION,
							clickedActivity.getDescription());
					showActivityIntent.putExtra(CLICKED_ACTIVITY_TIME_START,
							clickedActivity.getStartTime());
					showActivityIntent.putExtra(CLICKED_ACTIVITY_TIME_END,
							clickedActivity.getEndTime());
					showActivityIntent.putExtra(CLICKED_ACTIVITY_LATITUDE,
							clickedActivity.getLatitude());
					showActivityIntent.putExtra(CLICKED_ACTIVITY_LONGITUDE,
							clickedActivity.getLongitude());
					showActivityIntent.putExtra(CLICKED_ACTIVITY_ALTITUDE,
							clickedActivity.getAltitude());
					showActivityIntent.putExtra(RequestParameters.ID,
							clickedActivity.getId()+"");
					showActivityIntent.putExtra("fbeid",
							clickedActivity.getFacebookEventId()); //TODO add to request paramaeters in shard

					startActivity(showActivityIntent);

				}
			});
		}
		else 
		{
			Toast toast = Toast.makeText(this.getApplicationContext(),
					"No Activities found",
					Toast.LENGTH_SHORT);
			toast.show();
		}
	}

	/**
	 * Build a URL used in a HTTP POST request to create an activity. For the
	 * REST protocol specification see the REST interace specification document.
	 * 
	 * The general interface looks as follows:
	 */
	private URI getRequestUri() {

		List<NameValuePair> queryParams = new ArrayList<NameValuePair>();

		Double latitude, longitude;
		if (lastKnownLocation != null) {
			latitude = lastKnownLocation.getLatitude();
			longitude = lastKnownLocation.getLongitude();

		} else {
			latitude = mlocListener.getLatitude();
			longitude = mlocListener.getLongitude();
		}

		queryParams.add(new BasicNameValuePair(RequestParameters.LONGITUDE,
				longitude + ""));
		queryParams.add(new BasicNameValuePair(RequestParameters.LATITUDE,
				latitude + ""));
		queryParams.add(new BasicNameValuePair(RequestParameters.RANGE,
				ServerConfiguration.DEFAULT_RANGE + ""));
		queryParams.add(new BasicNameValuePair(RequestParameters.MAXRESULTS,
				ServerConfiguration.MAX_SEARCH_RESULTS + ""));

		try {
			return URIUtils.createURI("http",
					ServerConfiguration.ACTIVITY_SERVER, -1,
					"/search",
					URLEncodedUtils.format(queryParams, "UTF-8"), null);
		} catch (URISyntaxException e) {
			Log.e("SearchLocalActivities", QueryHelper.getStrackTrace(e));
			return null;
		}
	}

}
